const {
  think
} = require('thinkjs');
const Base = require('./base.js');
const moment = require('moment/moment.js');
const {
  default: BigNumber
} = require('bignumber.js');

module.exports = class extends Base {
  async listAction() {
    const page = this.get('page') || 1;
    const size = this.get('size') || 20;
    const query = this.get();
    let sort = ['name DESC'];

    delete query.page;
    delete query.size;

    // if (query.sortLabel) {
    //   sort = [
    //     `${query.sortLabel} ${
    //       query.sortValue === 'ascending' ? 'ASC' : 'DESC'
    //     }`,
    //   ];
    //   delete query.sortLabel;
    //   delete query.sortValue;
    // }

    if (query.project_id) {
      query['a.project_id'] = query.project_id;
      delete query.project_id;
    }

    query['a.type'] = 4;

    const data = await this.model('project_list')
      .alias('a')
      // .join({
      //   contract_list: {
      //     join: 'right',
      //     as: 'c',
      //     on: ['project_id', 'project_id'],
      //   },
      // })
      .where(query)
      .order(sort)
      .page(page, size)
      .field('a.*')
      .countSelect();

    // const contract = await this.model('contract_list')
    //   .where({
    //     type: 2,
    //     project_id: query.project_id,
    //   })
    //   .select();

    // if (!think.isEmpty(contract)) {
    //   const area = await this.model('project_list')
    //     .where(query)
    //     .sum('area');
    //   data.showErr = area != contract.area;
    //   data.contractArea = contract.area;
    //   data.area = area;
    // }
    data.tj = {};
    data.tj.areaTotal =
      (await this.model('project_list')
        .where({
          project_id: query['a.project_id'],
          type: 4,
        })
        .sum('area')) || 0;
    data.tj.areaZu =
      (await this.model('project_list')
        .where({
          project_id: query['a.project_id'],
          type: 4,
          status: 2,
        })
        .sum('area')) || 0;
    data.tj.numTotal = await this.model('project_list')
      .where({
        project_id: query['a.project_id'],
        type: 4,
      })
      .count();
    data.tj.numZu = BigNumber(data.tj.areaTotal)
      .minus(BigNumber(data.tj.areaZu))
      .toFixed();
    const chengbenAll = await this.model('project_list')
      .where({
        project_id: query['a.project_id'],
        type: 4,
        chengben_unit: ['!=', 0],
      })
      .sum('chengben_unit');
    const chengbenCount = await this.model('project_list')
      .where({
        project_id: query['a.project_id'],
        type: 4,
        chengben_unit: ['!=', 0],
      })
      .count();

    data.tj.chengben = BigNumber(chengbenAll)
      .div(BigNumber(chengbenCount))
      .toFixed(2);

    // const zujin =
    //   (await this.model('project_list')
    //     .where({
    //       project_id: query['a.project_id'],
    //       type: 4,
    //       status: 2,
    //     })
    //     .sum('zujin')) || 0;

    // data.tj.zujin = BigNumber(zujin)
    //   .div(BigNumber(data.tj.areaTotal))
    //   .toFixed(3);

    const lirunAll = await this.model('project_list')
      .where({
        project_id: query['a.project_id'],
        type: 4,
        lirun_unit: ['!=', 0],
      })
      .sum('lirun_unit');

    const lirunCount = await this.model('project_list')
      .where({
        project_id: query['a.project_id'],
        type: 4,
        lirun_unit: ['!=', 0],
      })
      .count();

    data.tj.lirun = BigNumber(lirunAll)
      .div(BigNumber(lirunCount))
      .toFixed(2);

    return this.success(data);
  }

  async originAction() {
    const page = this.get('page') || 1;
    const size = this.get('size') || 20;
    const query = this.get();
    let sort = ['name DESC'];

    delete query.page;
    delete query.size;

    // if (query.sortLabel) {
    //   sort = [
    //     `${query.sortLabel} ${
    //       query.sortValue === 'ascending' ? 'ASC' : 'DESC'
    //     }`,
    //   ];
    //   delete query.sortLabel;
    //   delete query.sortValue;
    // }

    if (query.project_id) {
      query['a.project_id'] = query.project_id;
      delete query.project_id;
    }

    query['a.type'] = 5;

    const data = await this.model('project_list')
      .alias('a')
      // .join({
      //   contract_list: {
      //     join: 'right',
      //     as: 'c',
      //     on: ['project_id', 'project_id'],
      //   },
      // })
      .where(query)
      .order(sort)
      .page(page, size)
      .field('a.*')
      .countSelect();

    // const contract = await this.model('contract_list')
    //   .where({
    //     type: 2,
    //     project_id: query.project_id,
    //   })
    //   .select();

    // if (!think.isEmpty(contract)) {
    //   const area = await this.model('project_list')
    //     .where(query)
    //     .sum('area');
    //   data.showErr = area != contract.area;
    //   data.contractArea = contract.area;
    //   data.area = area;
    // }
    data.tj = {};
    data.tj.areaTotal =
      (await this.model('project_list')
        .where({
          project_id: query['a.project_id'],
          type: 4,
        })
        .sum('area')) || 0;
    data.tj.areaZu =
      (await this.model('project_list')
        .where({
          project_id: query['a.project_id'],
          type: 4,
          status: 2,
        })
        .sum('area')) || 0;
    data.tj.numTotal = await this.model('project_list')
      .where({
        project_id: query['a.project_id'],
        type: 4,
      })
      .count();
    data.tj.numZu = BigNumber(data.tj.areaTotal)
      .minus(BigNumber(data.tj.areaZu))
      .toFixed();
    const chengbenAll = await this.model('project_list')
      .where({
        project_id: query['a.project_id'],
        type: 4,
        chengben_unit: ['!=', 0],
      })
      .sum('chengben_unit');
    const chengbenCount = await this.model('project_list')
      .where({
        project_id: query['a.project_id'],
        type: 4,
        chengben_unit: ['!=', 0],
      })
      .count();

    data.tj.chengben = BigNumber(chengbenAll)
      .div(BigNumber(chengbenCount))
      .toFixed(2);

    // const zujin =
    //   (await this.model('project_list')
    //     .where({
    //       project_id: query['a.project_id'],
    //       type: 4,
    //       status: 2,
    //     })
    //     .sum('zujin')) || 0;

    // data.tj.zujin = BigNumber(zujin)
    //   .div(BigNumber(data.tj.areaTotal))
    //   .toFixed(3);

    const lirunAll = await this.model('project_list')
      .where({
        project_id: query['a.project_id'],
        type: 4,
        lirun_unit: ['!=', 0],
      })
      .sum('lirun_unit');

    const lirunCount = await this.model('project_list')
      .where({
        project_id: query['a.project_id'],
        type: 4,
        lirun_unit: ['!=', 0],
      })
      .count();

    data.tj.lirun = BigNumber(lirunAll)
      .div(BigNumber(lirunCount))
      .toFixed(2);

    return this.success(data);
  }

  async putAction() {
    const id = this.post('id');
    const values = this.post();

    if (id > 0) {
      const editInfo = await this.model('project_list')
        .where({
          id: id
        })
        .find();
      // if (editInfo.area !== values.area && editInfo.status === 2) {
      //   return this.fail(401, '已出租的房源不支持修改面积');
      // }
      await this.model('project_list')
        .where({
          id: id
        })
        .update({
          addr: values.addr,
          origin_id: values.origin_id,
          area: values.area,
          beizhu: values.beizhu,
          huxing: values.huxing,
          remark: values.remark,
        });

      this.model('project_list')
        .where({
          id: editInfo.project_id
        })
        .update({
          addr: values.addr,
        });
    } else {
      delete values.id;
      // console.log(values);
      if (
        think.isEmpty(values.project_id) ||
        think.isEmpty(values.building_id) ||
        think.isEmpty(values.floor_id) ||
        think.isEmpty(values.name)
      ) {
        return this.fail(401, '项目信息不完善');
      }

      let addProject = values.project_id;
      let addBuilding = values.building_id;
      let addFloor = values.floor_id;
      let addOrigin = values.origin_id;

      if (
        !think.isNumber(values.project_id) ||
        !think.isNumber(values.building_id) ||
        !think.isNumber(values.floor_id)
      ) {
        if (!think.isNumber(values.project_id)) {
          addProject = await this.model('project_list').add({
            name: values.project_id,
            addr: values.addr,
            type: 1,
            create_time: ['exp', 'CURRENT_TIMESTAMP()'],
          });
        }
        if (!think.isNumber(values.building_id)) {
          addBuilding = await this.model('project_list').add({
            name: values.building_id,
            type: 2,
            project_id: addProject,
            create_time: ['exp', 'CURRENT_TIMESTAMP()'],
          });
        }

        if (!think.isNumber(values.floor_id)) {
          addFloor = await this.model('project_list').add({
            name: values.floor_id,
            type: 3,
            project_id: addProject,
            building_id: addBuilding,
            create_time: ['exp', 'CURRENT_TIMESTAMP()'],
          });
        }
      }

      const addId = await this.model('project_list').add({
        name: values.name,
        type: 4,
        project_id: addProject,
        building_id: addBuilding,
        floor_id: addFloor,
        origin_id: addOrigin,
        area: values.area,
        // huxing: values.huxing,
        remark: values.remark,
        create_time: ['exp', 'CURRENT_TIMESTAMP()'],
      });

      const p = await this.model('project_list')
        .where({
          project_id: addProject,
          type: 1
        })
        .find();

      if (p.addr) {
        this.model('project_list')
          .where({
            id: addId,
            type: 4
          })
          .update({
            addr: p.addr,
          });
      }

      // const contract = await this.model('contract_list')
      //   .where({ project_id: addProject })
      //   .find();
      // if (!think.isEmpty(contract)) {
      //   const currentRoom = await this.model('project_list')
      //     .where({ project_id: addProject, type: 4, average: ['!=', null] })
      //     .find();

      //   const cost = BigNumber(currentRoom.average).times(
      //     BigNumber(values.area)
      //   );
      //   await this.model('project_list')
      //     .where({ id: addId })
      //     .update({
      //       chengben: cost.toFixed(2),
      //       average: currentRoom.average,
      //       status: 1,
      //     });
      // }
    }
    return this.success();
  }

  async putOriginAction() {
    const id = this.post('id');
    const values = this.post();

    if (id > 0) {
      const editInfo = await this.model('project_list')
        .where({
          id: id
        })
        .find();
      if (editInfo.area !== values.area && editInfo.status === 2) {
        return this.fail(401, '已出租的房源不支持修改面积');
      }
      await this.model('project_list')
        .where({
          id: id
        })
        .update({
          addr: values.addr,
          area: values.area,
          beizhu: values.beizhu,
          huxing: values.huxing,
          remark: values.remark,
        });

      this.model('project_list')
        .where({
          id: editInfo.project_id
        })
        .update({
          addr: values.addr,
        });
    } else {
      delete values.id;
      // console.log(values);
      if (
        think.isEmpty(values.project_id) ||
        think.isEmpty(values.building_id) ||
        think.isEmpty(values.floor_id) ||
        think.isEmpty(values.name)
      ) {
        return this.fail(401, '项目信息不完善');
      }

      let addProject = values.project_id;
      let addBuilding = values.building_id;
      let addFloor = values.floor_id;

      if (
        !think.isNumber(values.project_id) ||
        !think.isNumber(values.building_id) ||
        !think.isNumber(values.floor_id)
      ) {
        if (!think.isNumber(values.project_id)) {
          addProject = await this.model('project_list').add({
            name: values.project_id,
            addr: values.addr,
            type: 1,
            create_time: ['exp', 'CURRENT_TIMESTAMP()'],
          });
        }
        if (!think.isNumber(values.building_id)) {
          addBuilding = await this.model('project_list').add({
            name: values.building_id,
            type: 2,
            project_id: addProject,
            create_time: ['exp', 'CURRENT_TIMESTAMP()'],
          });
        }

        if (!think.isNumber(values.floor_id)) {
          addFloor = await this.model('project_list').add({
            name: values.floor_id,
            type: 3,
            project_id: addProject,
            building_id: addBuilding,
            create_time: ['exp', 'CURRENT_TIMESTAMP()'],
          });
        }
      }

      const addId = await this.model('project_list').add({
        name: values.name,
        type: 5,
        project_id: addProject,
        building_id: addBuilding,
        floor_id: addFloor,
        area: values.area,
        huxing: values.huxing,
        remark: values.remark,
        create_time: ['exp', 'CURRENT_TIMESTAMP()'],
      });

      const p = await this.model('project_list')
        .where({
          project_id: addProject,
          type: 1
        })
        .find();

      if (p.addr) {
        this.model('project_list')
          .where({
            id: addId,
            type: 4
          })
          .update({
            addr: p.addr,
          });
      }

      // const contract = await this.model('contract_list')
      //   .where({ project_id: addProject })
      //   .find();
      // if (!think.isEmpty(contract)) {
      //   const currentRoom = await this.model('project_list')
      //     .where({ project_id: addProject, type: 4, average: ['!=', null] })
      //     .find();

      //   const cost = BigNumber(currentRoom.average).times(
      //     BigNumber(values.area)
      //   );
      //   await this.model('project_list')
      //     .where({ id: addId })
      //     .update({
      //       chengben: cost.toFixed(2),
      //       average: currentRoom.average,
      //       status: 1,
      //     });
      // }
    }
    return this.success();
  }

  async orderAction() {
    const page = this.get('page') || 1;
    const size = this.get('size') || 20;
    const query = this.get();

    delete query.page;
    delete query.size;

    query.type = 4;

    const data = await this.model('contract_list')
      .where(query)
      .order(['id DESC'])
      .page(page, size)
      .countSelect();

    return this.success(data);
  }

  async roomAreaAction() {
    const arr = this.post('arr');
    const type = this.post('type');
    if (type === 'floor') {
      const num = await this.model('project_list')
        .where({
          floor_id: ['IN', arr]
        })
        .sum('area');
      return this.success(num);
    } else {
      const num = await this.model('project_list')
        .where({
          id: ['IN', arr]
        })
        .sum('area');
      return this.success(num);
    }
  }

  async projectAreaAction() {
    const arr = this.post('project_id');
    if (think.isEmpty(arr)) {
      return this.success(0);
    }
    const f = [];
    for (const item of arr) {
      if (item.length === 3) {
        f.push(item[2]);
      }
    }
    const num = await this.model('project_list')
      .where({
        floor_id: ['IN', f],
        type: 4
      })
      .sum('area');
    return this.success(num);
  }

  async guakaoAction() {
    const data = await this.model('guakao_list')
      .where({
        room_id: this.get('room_id'),
        status: 1,
      })
      .order(['id DESC'])
      .select();

    return this.success(data);
  }

  async endGuakaoAction() {
    const data = await this.model('guakao_list')
      .where({
        id: this.get('id'),
      })
      .update({
        status: 0,
      });

    return this.success(data);
  }

  // 甲方房源成本
  async chengbenAction() {
    await this.model('jisuan').jiafang(this.get('id'));
    return this.success();
  }

  //合同成本
  async reloadCbAction() {
    const list = await this.model('contract_list')
      .where({
        type: 1,
        status: 1
      })
      .select();

    for (const item of list) {
      const arr = JSON.parse(item.project);
      const room = [];
      for (const itemRoom of arr) {
        room.push(itemRoom[3]);
      }
      const chengben = await this.model('project_list')
        .where({
          id: ['IN', room]
        })
        .sum('chengben');
      // console.log(chengben);

      const months = moment(item.date_end)
        .add(1, 'days')
        .diff(moment(item.date_start), 'month');

      const newChengben = BigNumber(chengben)
        .times(BigNumber(months))
        .toFixed(2);
      await this.model('contract_list')
        .where({
          id: item.id
        })
        .update({
          chengben: newChengben,
        });
    }
    return this.success();
  }
  //房源租金
  async shouruAction() {
    return this.success();
  }

  async yueAction() {
    return this.success();
  }

  async baseChengbenAction() {
    // this.model('jisuan').zhuangxiu();
    return this.success();
  }
};